package com.golddaymicromall.activity.notice;

import android.content.Intent;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.adapter.NoticeAdapter;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.NoticeInfo;
import com.golddaymicromall.module.ListViewLoadMore;
import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class NoticeActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, ListViewLoadMore.IsLoadingListener {
    private ListViewLoadMore mlv;
    private NoticeAdapter adapter;
    private List<NoticeInfo> list;

    private int CurrentPageNum = 0;
    private LinearLayout mNoticeBack;
    private Handler handler = new Handler();
    private List<NoticeInfo> listAll = new ArrayList<NoticeInfo>();
    ProgressBar progress;
    private String Customerno;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice);
        initView();
        Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();

        CurrentPageNum = 1;
        attemptNotice(CurrentPageNum);
    }

    private void initView() {
        progress = (ProgressBar) findViewById(R.id.progress);
        list = new ArrayList<NoticeInfo>();
        mlv = (ListViewLoadMore) findViewById(R.id.noticeLv);
        mlv.setOnItemClickListener(this);
        mlv.setOnLoadingListener(this);
        mNoticeBack = (LinearLayout) findViewById(R.id.noticeBack);
        mNoticeBack.setOnClickListener(this);
    }

    private void attemptNotice(int CurrentPageNum) {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.notice.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("target", Customerno);
        form.put("current_pagenum", String.valueOf(CurrentPageNum));
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(NoticeActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(NoticeActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list = JSON.parseArray(result, NoticeInfo.class);
                            if (CurrentPageNum > 1) {
                                listAll.addAll(list);
                            } else if (CurrentPageNum == 1) {
                                listAll.clear();
                                listAll.addAll(list);
                            }
                            Collections.sort(listAll, (lhs, rhs) -> {
                                Date date1 = lhs.getBegindate();
                                Date date2 = rhs.getBegindate();
                                // 对日期字段进行升序，如果欲降序可采用after方法
                                if (date1.before(date2)) {
                                    return 1;
                                }
                                return -1;
                            });
                            adapter = new NoticeAdapter(listAll, NoticeActivity.this);
                            mlv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            if (CurrentPageNum > 1) {
                                mlv.setSelection(mlv.getCount() - 1);
                            }

                        }
                    } else {
                        Toast.makeText(NoticeActivity.this, "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.noticeBack:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, NoticeContentActivity.class);

        intent.putExtra("Content", listAll.get(position).getContent());
        startActivity(intent);
    }

    @Override
    public void onLoad() {
        handler.postDelayed(() -> {
            CurrentPageNum++;
            attemptNotice(CurrentPageNum);

            adapter.notifyDataSetChanged();
            mlv.complateLoad();
        }, 3000);
    }
}
